module.exports = function (io) {
    let userData = {},
        memberNum = 0;

    io.on('connection', (socket) => {
        console.log('连接成功')

        // 用户加入群聊
        socket.on('join', (name, avatar) => {
            userData[name] = socket.id
            socket.name = name
            memberNum += 1
            let msgData = {
                name,
                avatar,
                memberNum,
                time: new Date()
            }
            // 广播新用户加入群聊
            socket.broadcast.emit('welcome', msgData)
            socket.emit('myself', msgData)
        })

        // 用户发送信息
        socket.on('sendMsg', data => {
            // 广播除当前发信息用户外的用户
            socket.broadcast.emit('getMsg', data)
        })

        // 用户离开
        socket.on('disconnecting', () => {
            delete userData[socket.name]
            memberNum--

            // 广播离开的用户
            socket.broadcast.emit('quit', socket.name, memberNum)
        })
    })
}